package com.cosfly.sharemusic.common;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.*;
import java.security.MessageDigest;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class BaseUtil {
    /**
     * 字符串MD5加密,生产32位MD5字符串
     */
    public static String md5Encode(String inStr) throws Exception {
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (Exception e) {
            System.out.println(e.toString());
            e.printStackTrace();
            return "";
        }

        byte[] byteArray = inStr.getBytes("UTF-8");
        byte[] md5Bytes = md5.digest(byteArray);
        StringBuffer hexValue = new StringBuffer();
        for (int i = 0; i < md5Bytes.length; i++) {
            int val = ((int) md5Bytes[i]) & 0xff;
            if (val < 16) {
                hexValue.append("0");
            }
            hexValue.append(Integer.toHexString(val));
        }
        return hexValue.toString();
    }

    /**
     * 删除文件目录下的文件
     *
     * @param dirPath
     */
    public static void deleteDir(String dirPath) {
        File file = new File(dirPath);// 读取
        if (file.isFile()) { // 判断是否是文件夹
            file.delete();// 删除
        } else {
            File[] files = file.listFiles(); // 获取文件
            if (files == null) {
                file.delete();// 删除
            } else {
                for (int i = 0; i < files.length; i++) {// 循环
                    deleteDir(files[i].getAbsolutePath());
                }
                file.delete();// 删除
            }
        }
    }

    /**
     * 图片转化成base64字符串
     *
     * @return
     */
    public static String GetImageStr(String imgFile) {
        //将图片文件转化为字节数组字符串，并对其进行Base64编码处理
        InputStream in = null;
        byte[] data = null;
        //读取图片字节数组
        try {
            in = new FileInputStream(imgFile);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(data);//返回Base64编码过的字节数组字符串
    }

    /**
     * base64字符串转化成图片
     *
     * @param imgStr
     * @return
     */
    public static boolean GenerateImage(String imgStr, String imgFile) {
        String path = Thread.currentThread().getContextClassLoader().getResource("").getPath();//获取当前资源的虚拟路径
        //对字节数组字符串进行Base64解码并生成图片
        if (imgStr == null) //图像数据为空
            return false;
        BASE64Decoder decoder = new BASE64Decoder();
        imgStr = imgStr.substring(23, imgStr.length() - 1);
        try {
            //Base64解码
            byte[] b = decoder.decodeBuffer(imgStr);
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {//调整异常数据
                    b[i] += 256;
                }
            }
            //生成jpeg图片
            OutputStream out = new FileOutputStream(path + "/" + imgFile);
            out.write(b);
            out.flush();
            out.close();
            return true;
        } catch (Exception e) {
            System.out.println(e);
            return false;
        }
    }

    /**
     * 验证邮箱地址是否正确
     * @param email
     * * @return
     */
    public static boolean checkEmail(String email){
        boolean flag = false;
        try {
            String check = "^（[a-z0-9A-Z]+[-|\\.]?）+[a-z0-9A-Z]@（[a-z0-9A-Z]+（-[a-z0-9A-Z]+）？\\.）+[a-zA-Z]{2,}$";
            Pattern regex = Pattern.compile(check);
            Matcher matcher = regex.matcher(email);
            flag = matcher.matches();
        } catch(Exception e){
            flag = false;
        }
        return flag;
    }

    /**
     * 验证手机号码
     * @param mobiles
     * @return  [0-9]{5,9}
     */
    public static boolean isMobileNO(String mobiles) {
        boolean flag = false;
        try {
            Pattern p = Pattern.compile("^（（13[0-9]）|（15[^4,\\D]）|（18[0,5-9]））\\d{8}$");
            Matcher m = p.matcher(mobiles);
            flag = m.matches();
        } catch(Exception e){
            flag = false;
        }
        return flag;
    }
}
